package com.cily.utils.t_webrtc.pad;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cily.utils.app.utils.SpUtils;
import com.cily.utils.base.time.TimeUtils;
import com.cily.utils.log.L;
import com.cily.utils.media.Player;
import com.cily.utils.t_webrtc.BaseAc3;
import com.cily.utils.t_webrtc.BuildConfig;
import com.cily.utils.t_webrtc.Conf;
import com.cily.utils.t_webrtc.LoginAc;
import com.cily.utils.t_webrtc.R;
import com.cily.utils.t_webrtc.bean.ActionBean;
import com.cily.utils.t_webrtc.utils.StrMsgUtils;
import com.cily.utils.t_webrtc.utils.WsUtils;
import com.google.zxing.WriterException;
import com.zxing.encoding.EncodingHandler;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class PhoneWaitAc extends BaseAc3 {
    LinearLayout ll;
    String roomId;  //被呼叫者的物理房间号
    Player player;
    private String userRoom;
    private int type_call = Conf.ACTION_CALL_VIDEO;
    private boolean callByUser = false;
    public final static String TIME_STRAP = "yyyy_MM_dd_HH_mm_ss";
    private ImageView img_barcode;
    String time = null;
    Bitmap qrCodeBitmap = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_phone_wait);
        userRoom = SpUtils.getStr(this, Conf.USER_ROOM, "");


        TextView tv = findView(R.id.tv_user_room);
        tv.setText(userRoom);

        img_barcode = findView(R.id.img_barcode);

        ll = findView(R.id.ll_option);
        findBtn(R.id.btn_answer).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toVideo();
            }
        });
        findBtn(R.id.btn_hold).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WsUtils.sendMsg(StrMsgUtils.hold(userRoom, roomId));
                cancelTimer();
            }
        });
        findBtn(R.id.btn_denine).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WsUtils.sendMsg(StrMsgUtils.refuse(userRoom, roomId));
                cancelTimer();
                stop();

                next(null);
            }
        });


        findBtn(R.id.btn_create_barcode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                time = TimeUtils.milToStr(System.currentTimeMillis(), TIME_STRAP);
                try {
                    qrCodeBitmap = EncodingHandler.createQRCode(time, 350);
                    img_barcode.setImageBitmap(qrCodeBitmap);
                } catch (WriterException e) {
                    L.printException(e);
                    showToast("生成二维码失败");
                }
            }
        });


        findBtn(R.id.btn_save_barcode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (qrCodeBitmap == null){
                    showToast("先生成二维码，再保存");
                    return;
                }

                saveMyBitmap(time, qrCodeBitmap);
            }
        });

        LinearLayout ll_set = findView(R.id.ll_set);
        if (BuildConfig.TYPE_APP == 1){
            ll_set.setVisibility(View.VISIBLE);

            findBtn(R.id.btn_logout).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    logout();
                }
            });

            findBtn(R.id.btn_setting).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    toAc(SettingsActivity.class, null);
                }
            });
        }
    }

    private Bitmap getTransparentBitmap(Bitmap sourceImg, int number){
        int[] argb = new int[sourceImg.getWidth() * sourceImg.getHeight()];

        sourceImg.getPixels(argb, 0, sourceImg.getWidth(), 0, 0, sourceImg
                .getWidth(), sourceImg.getHeight());// 获得图片的ARGB值
        number = number * 255 / 100;

        for (int i = 0; i < argb.length; i++) {
            argb[i] = (number << 24) | (argb[i] & 0x00FFFFFF);
        }
        sourceImg = Bitmap.createBitmap(argb, sourceImg.getWidth(), sourceImg
                .getHeight(), Bitmap.Config.ARGB_8888);
        return sourceImg;
    }

    private void saveMyBitmap(String bitName, Bitmap mBitmap){
        if(!Environment.isExternalStorageEmulated()){
            showToast("没找到SD卡，无法存储二维码");
            return;
        }

        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath();
        String fileName = filePath + File.separator + bitName + ".jpg";
        File f = new File(fileName);
        try {
            f.createNewFile();
        } catch (IOException e) {
            L.printException(e);
            showToast("保存图片失败");
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
            mBitmap.compress(Bitmap.CompressFormat.PNG, 90, fOut);
            fOut.flush();

            showToast("二维码保存在(" + fileName + ")");
        } catch (FileNotFoundException e) {
            L.printException(e);
        } catch (IOException e) {
            L.printException(e);
        } finally {
            try {
                if (fOut != null) {
                    fOut.close();
                }
            } catch (IOException e) {
                L.printException(e);
            }
        }
    }

    private void logout(){
        WsUtils.stopWs(this);

        toAc(LoginAc.class, null);
        finish();
    }

    private String iceCandidate;
    private void toVideo(){
        cancelTimer();
        stop();

        Bundle b = new Bundle();
        b.putString(Conf.EXTRA_ROOMID, roomId);
        b.putInt(Conf.INTENT_CALL_TYPE, type_call);
        b.putString(Conf.INTENT_ICECANDIDATE, iceCandidate);
        toAc(VideoAc.class, b);

        if (BuildConfig.TYPE_APP == 0){
            finish();
        }else if (BuildConfig.TYPE_APP == 1){
            ll.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

        boolean fromPadCall = getIntent().getBooleanExtra(Conf.INTENT_FROM_PAD, false);
        callByUser = getIntent().getBooleanExtra(Conf.INTENT_CALL_BY_USER, false);
        if (fromPadCall){
            roomId = getIntent().getStringExtra(Conf.EXTRA_ROOMID);
            WsUtils.sendMsg(StrMsgUtils.callVedio(userRoom, roomId, null));
            startTimer();
        }

        if (callByUser){
            roomId = getIntent().getStringExtra(Conf.EXTRA_ROOMID);
            startTimer();
            ll.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void doResponse(Object b) {
        mHandler.sendMessage(mHandler.obtainMessage(0, b));
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.obj instanceof ActionBean){
                ActionBean b = (ActionBean)msg.obj;
//                showToast(b.toString());
                if (b != null){
                    roomId = b.getSenderRoomNumber();
                    int code = b.getCode();

                    if (code == Conf.ACTION_CALL_VIDEO || code == Conf.ACTION_CALL_VOICE){
                        startTimer();
                        ll.setVisibility(View.VISIBLE);
                        type_call = code;
                        iceCandidate = b.getContent();
                    }else if (code == Conf.ACTION_BUSY){
                        next("对方忙，请稍后呼叫");
                    }else if (code == Conf.ACTION_REFUSE){
                        next("拒绝接听");
                    }else if (code == Conf.ACTION_USER_NOT_EXIST){
                        next("该房间为空号");
                    }else if (code == Conf.ACTION_HUNG_UP){
                        next("聊天已结束");
                    }else if (code == Conf.ACTION_ERROR){
                        next("未知错误，聊天已结束");
                    }else if (code == Conf.ACTION_AGREE){
                        //接听
                        showToast("同意接听");
                        toVideo();
                    }else if (code == Conf.ACTION_HOLD){
                        cancelTimer();
                    }
                }
            }
        }
    };

    private void next(String str){
        stop();
        cancelTimer();

        showToast(str);
        if (BuildConfig.TYPE_APP == 0){
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, 2000);
        }else if (BuildConfig.TYPE_APP == 1){
            ll.setVisibility(View.GONE);
        }
    }
}